<template>
	<view style="padding-bottom: 130rpx;">
		<view class="formContainer">
			<uni-forms ref="form">
				<uni-forms-item label="还车日期" required>
					<view style="color: #333;font-size: 28rpx;">
						<uni-datetime-picker type="datetime" v-model="returnTime" :start="rentalEndTime" @change="timeChange" />
						<template v-if="dataType == 1">
							<text style="font-size: 26rpx;color: #ff3336;flex-grow: 1;">续租{{ renewDays }}天</text>
						</template>
						<template v-else-if="dataType == 2">
							<text v-if="costInfo" style="font-size: 26rpx;color: #ff3336;flex-grow: 1;">续租{{ costInfo.days }}天</text>
						</template>
						
					</view>
				</uni-forms-item>

				<uni-forms-item label="费用总计" required>
					<view><u--input v-model="totalRent" placeholder="自动计算不可修改" disabled></u--input></view>
				</uni-forms-item>

				<block v-if="tableData.length > 0">
					<view v-for="(item, index) in tableData" :key="index" style="margin: 20rpx; 0">
						<!-- 费用项标题及操作按钮 -->
						<view class="flex-row-center-sb" style="margin-bottom: 20rpx;">
							<text style="font-size: 28rpx;color: #666;">{{ item.chargeProjectName }}</text>
							
							<block v-if="item.isRent == 1">
								<text style="font-size: 26rpx;color: #2879FF;" @click.stop="showRentDetail = !showRentDetail">
									日租金明细
								</text>
							</block>
							<block v-else>
								<view class="flex-row" v-if="item.canEdit != 1">
									<u-switch v-if="item.isOptional == 1" v-model="item.selected" size="20"></u-switch>
									<!-- 编辑按钮 -->
									<view
										v-if="item.canEdit == 3"
										style="margin-right: 20rpx;margin-left: 20rpx;"
										@click="editCostItem(2, index, item)"
									>
										<u-icon name="edit-pen" color="#2879FF" size="24"></u-icon>
									</view>
									<!-- 删除按钮 -->
									<view @click="deleteCostItem(index)">
										<u-icon name="trash" color="#2879FF" size="24"></u-icon>
									</view>
								</view>
							</block>
						</view>

						<uni-table ref="table" :loading="loading" border stripe>
							<uni-tr>
								<uni-th width="100" align="center"><text style="color: #2879FF;">单价</text></uni-th>
								<uni-th width="100" align="center"><text style="color: #2879FF;">数目</text></uni-th>
								<uni-th width="100" align="center"><text style="color: #2879FF;">费用</text></uni-th>
							</uni-tr>
							<uni-tr>
								<uni-td align="center">{{ item.unitPrice }}{{ item.chargeItemsType | chargeItemsType }}</uni-td>
								<uni-td align="center">{{ item.number }}</uni-td>
								<uni-td align="center">{{ item.unitPrice * item.number }}</uni-td>
							</uni-tr>
						</uni-table>
					</view>

					<view class="flex-xy-center">
						<view class="flex-row-center addCost" @click="editCostItem(1)">
							<u-icon name="plus-circle" color="#fff"></u-icon>
							<text style="color: #fff;font-size: 26rpx;margin-left: 20rpx;">添加收费项</text>
						</view>
					</view>
				</block>
			</uni-forms>
		</view>

		<!-- 新增收费项弹框 -->
		<u-popup :show="showEditCost" mode="bottom" @close="showEditCost = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx 20rpx;">
				<view style="margin-bottom: 30rpx;">{{ popTitleType == 1 ? '新增' : '编辑' }}收费项</view>
				<uni-forms ref="form">
					<uni-forms-item label="收费项名称" labelWidth="90" required>
						<view>
							<u--input
								v-model="customCost.chargeProjectName"
								:disabled="customCost.canEdit != 3"
								placeholder="请输入收费项名称"
							></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="收费类型" required>
						<uni-data-checkbox
							v-model="customCost.chargeItemsType"
							:disabled="customCost.canEdit != 3"
							:localdata="chargeItemsTypes"
						/>
					</uni-forms-item>

					<uni-forms-item label="单价" type="number" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.unitPrice" @input="check" type="digit" placeholder="请输入单价"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="数目" labelWidth="90" required>
						<view><u--input v-model="customCost.number" type="number" placeholder="请输入数量"></u--input></view>
					</uni-forms-item>

					<uni-forms-item label="费用合计" labelWidth="90">
						<view>
							<text style="position: relative;top: 15rpx;">{{ customCost.number * customCost.unitPrice || '0' }}</text>
						</view>
					</uni-forms-item>
				</uni-forms>

				<view class="commitBtn" @click="commitCost">提交</view>
			</view>
		</u-popup>

		<u-popup :show="showRentDetail" mode="center" @close="showRentDetail = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx">
				<view style="margin-bottom: 30rpx;">费用租赁明细</view>
				<scroll-view scroll-y="true">
					<view style="max-height: 800rpx;">
						<view class="flex-row-center-sb payCostItem" v-for="(item, index) in planPriceVoList" :key="index">
							<text>{{ dataType == 1 ? item.sameDay : item.time }}</text>
							<text>{{ item.price }}元</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<button type="info" class="sub-btn" @click="confimRelet">保存</button>
	</view>
</template>

<script>
import * as orderApi from '@/api/order-api.js';
export default {
	data() {
		return {
			rentalEndTime: null,
			orderNo: '',
			returnTime: this.parseTime(new Date()), //还车时间
			costInfo: null,
			dayliyRent: '',
			showEditCost: false,
			showRentDetail: false, //日租金明细
			tableData: [],
			currentEditCostIndex: -1,
			popTitleType: 1,
			customCost: {
				chargeProjectName: 0,
				chargeMoney: '',
				chargeItemsType: 1,
				canEdit: 3,
				number: '',
				unitPrice: '',
				isRent: 2,
				chargeProjectCategory: 9
			},
			planPriceVoList: [],
			chargeItemsTypes: [
				{
					value: 1,
					text: '按次'
				},
				{
					value: 2,
					text: '按天'
				},
				{
					value: 6,
					text: '按个'
				}
			],
			reletId : '',//编辑续租id
			dataType:1 ,//1回显 2编辑,
			renewDays : 0,//回显续租天数
		};
	},
	computed: {
		totalRent() {
			var totalRent = 0;
			this.tableData.map(item => {
				if (item.selected) {
					totalRent += Number(item.chargeMoney);
				}
			});
			return totalRent;
		}
	},
	onLoad(op) {
		this.reletId = op.id;
		this.getRenewRecordInfo();
	},
	methods: {
		// 获取编辑回显数据
		getRenewRecordInfo(){
			orderApi.renewRecordInfo(this.reletId).then(res=>{
				const data = res.data.renewRecord;
			   this.orderNo = data.orderNo;
			   this.rentalEndTime = data.beforeTime;
			   this.returnTime = this.parseTime(data.afterTime);
			   this.renewDays = data.renewDays;
			   
			   
			   this.costInfo = data.cost;
			   this.tableData = this.costInfo.orderChargingItems;
			   this.tableData.map(item => {
			   	item.selected = true;
			   });
			   this.dayliyRent = data.renewCost / data.renewDays;
			   this.planPriceVoList = this.costInfo.orderPriceCalendars;
			   this.planPriceVoList = this.planPriceVoList.map(item=>{
				   this.$set(item, 'time', item.sameDay);
				   this.$set(item, 'type', 1);
				   return item;
			   })
			   
			})
		},
		check(e) {
			//正则表达试
			e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
			this.$nextTick(() => {
				this.customCost.unitPrice = e;
			});
		},
		// 选择还车时间
		timeChange(e) {
			this.returnTime = this.parseTime(e);
			this.getRenewalFee();
		},

		// 查询费用信息
		getRenewalFee() {
			orderApi
				.renewalFee({
					orderNo: this.orderNo,
					takeAlsoTime: this.returnTime,
					renewRecordId: this.reletId
				})
				.then(res => {
					this.costInfo = res.data;
					this.dataType = 2;
					this.tableData = this.costInfo.chargingItemsVoList;
					this.tableData.map(item => {
						item.selected = true;
					});
					this.dayliyRent = this.costInfo.rent / this.costInfo.days;
					this.planPriceVoList = this.costInfo.planPriceVoList;
				});
		},
		// 删除费用项
		deleteCostItem(index) {
			this.tableData.splice(index, 1);
		},

		// 添加或者编辑自定义费用项
		editCostItem(type, index, info) {
			this.popTitleType = type;
			if (type == 1) {
				//新增
				this.customCost = {
					chargeProjectName: '',
					chargeMoney: '',
					chargeItemsType: 1,
					canEdit: 3,
					number: '',
					unitPrice: '',
					isRent: 2,
					chargeProjectCategory: 9,
					selected: true,
					calculate: ''
				};
			} else {
				//编辑
				this.customCost = info;
				this.currentEditCostIndex = index;
			}
			this.showEditCost = true;
		},
		//确定提交费用项
		commitCost() {
			if (uni.$u.test.isEmpty(this.customCost.chargeProjectName)) {
				uni.$u.toast('请输入费用项名称');
				return;
			} else if (uni.$u.test.isEmpty(this.customCost.unitPrice)) {
				uni.$u.toast('请输入单价');
				return;
			} else if (uni.$u.test.isEmpty(this.customCost.number)) {
				uni.$u.toast('请输入数目');
				return;
			} else if (this.customCost.number == '0') {
				uni.$u.toast('数目不能为0,请重新输入');
				return;
			} else {
				if (this.popTitleType == 1) {
					//新增
					this.customCost.chargeMoney = Number(this.customCost.unitPrice) * Number(this.customCost.number);
					this.tableData.push(this.customCost);
					console.log(this.tableData);
				} else {
					//编辑
					this.tableData[this.currentEditCostIndex].chargeProjectName = this.customCost.chargeProjectName;
					this.tableData[this.currentEditCostIndex].unitPrice = this.customCost.unitPrice;
					this.tableData[this.currentEditCostIndex].number = this.customCost.number;
					this.tableData[this.currentEditCostIndex].chargeItemsType = this.customCost.chargeItemsType;
					this.tableData[this.currentEditCostIndex].canEdit = this.customCost.canEdit;
					this.tableData[this.currentEditCostIndex].chargeMoney =
						Number(this.customCost.unitPrice) * Number(this.customCost.number);
					this.tableData[this.currentEditCostIndex].calculate = this.customCost.unitPrice + '×️';
					this.customCost.number;
					this.tableData[this.currentEditCostIndex].isRent = this.customCost.isRent;
				}

				this.showEditCost = false;
			}
		},

		confimRelet() {
			if (uni.$u.test.isEmpty(this.returnTime)) {
				uni.$u.toast('请选择还车日期');
				return;
			} else {
				uni.showModal({
					title: '提示',
					content: '确定保存续租吗?',
					cancelText: '取消',
					confirmText: '确认保存',
					success: res => {
						if (res.confirm) {
							uni.showLoading({
								title:'保存中...'
							})
							orderApi
								.renewRecordEdit({
									chargeItemsVo: this.tableData,
									planPriceVoList: this.planPriceVoList,
									leaseDays: this.dataType == 1? this.renewDays : this.costInfo.days,
									orderNo: this.orderNo,
									payType: 1,
									payWay: 1,
									rent: this.totalRent,
									rentalEndTime: this.parseTime(this.returnTime),
									renewRecordId: this.reletId,
								})
								.then(res => {
									uni.hideLoading();
									uni.$emit('refreshOrder');
									this.$u.toast('保存成功');
									uni.navigateBack({
										animationDuration: 300
									});
								});
						}
					}
				});
			}
		},

		// 日期格式化
		parseTime(time, pattern) {
			if (arguments.length === 0 || !time) {
				return null;
			}
			const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
			let date;
			if (typeof time === 'object') {
				date = time;
			} else {
				if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
					time = parseInt(time);
				} else if (typeof time === 'string') {
					time = time
						.replace(new RegExp(/-/gm), '/')
						.replace('T', ' ')
						.replace(new RegExp(/\.[\d]{3}/gm), '');
				}
				if (typeof time === 'number' && time.toString().length === 10) {
					time = time * 1000;
				}
				date = new Date(time);
			}
			const formatObj = {
				y: date.getFullYear(),
				m: date.getMonth() + 1,
				d: date.getDate(),
				h: date.getHours(),
				i: date.getMinutes(),
				s: date.getSeconds(),
				a: date.getDay()
			};
			const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
				let value = formatObj[key];
				// Note: getDay() returns 0 on Sunday
				if (key === 'a') {
					return ['日', '一', '二', '三', '四', '五', '六'][value];
				}
				if (result.length > 0 && value < 10) {
					value = '0' + value;
				}
				return value || 0;
			});
			return time_str;
		}
	}
};
</script>

<style lang="scss" scoped>
.formContainer {
	margin: 40rpx 20rpx;
	padding: 24rpx;
	background-color: #fff;
	box-shadow: 0px 4rpx 16rpx 0px rgba(1, 10, 18, 0.1);
	border-radius: 16rpx;
}

.addCost {
	margin: 32rpx 0;
	box-sizing: border-box;
	padding-left: 30rpx;
	width: 242rpx;
	height: 60rpx;
	background: #1673ff;
	border-radius: 30rpx;
}

.payCostItem {
	height: 80rpx;
	width: 600rpx;
	border-bottom: 1rpx solid #ededed;
	font-size: 28rpx;
	color: #333;
}

.commitBtn {
	background-color: #1673ff;
	border-radius: 12rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	color: #fff;
	width: 300rpx;
	margin-top: 30rpx;
}
</style>
